const express = require('express')
const router = express.Router()
const {Category} = require('../../models')
const {Op} = require('sequelize')
const {NotFoundError, success, failure} = require('../../utils/response')

/**
 * 查询分类列表
 * GET /admin/categories
 */
router.get('/', async (req, res) => {
	try {
		const query = req.query

		// 当前页码，如果不传，默认为1
		const currentPage = Math.abs(Number(query.currentPage)) || 1
		// 每页显示条数，如果不传，默认为10
		const pageSize = Math.abs(Number(query.pageSize)) || 10
		// 计算 offset
		const offset = (currentPage - 1) * pageSize

		const condition = {
			order: [['id', 'desc']], limit: pageSize, offset: offset
		}

		// 搜索
		if (query.name) {
			condition.where = {
				name: {
					[Op.like]: `%${query.name}%`
				}
			}
		}

		const {count, rows} = await Category.findAndCountAll(condition)

		success(res, '后台分类列表接口', {
			categories: rows, pagination: {
				total: count, currentPage, pageSize
			}
		})
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 分类详情查询
 * GET /admin/categories/1
 */
router.get('/:id', async (req, res) => {
	try {
		const category = await getCategorys(req)
		success(res, '后台分类列表接口', category)
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 创建分类
 * POST /admin/categories
 */
router.post('/', async (req, res) => {
	try {
		// 过滤白名单
		const body = filterBody(req)
		const category = await Category.create(body)
		success(res, '创建分类成功', category, 201)
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 删除分类
 * DELETE /admin/categories/:id
 * @type {Router}
 */
router.delete('/:id', async (req, res) => {
	try {
		const id = req.params.id
		const category = await getCategorys(req)
		await Category.destroy({where: {id}})
		success(res, '删除分类成功')
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 更新分类
 * PUT /admin/categories/:id
 * @type {Router}
 */
router.put('/:id', async (req, res) => {
	try {
		const {id} = req.params
		const category = await getCategorys(req)
		const body = filterBody(req)
		await Category.update(body, {where: {id}})
		success(res, '更新分类成功')
	} catch (e) {
		failure(res, e)
	}
})

/**
 * 公共方法：查询分类
 * @param req
 * @returns {Promise<Model>}
 */
async function getCategorys(req) {
	const {id} = req.params
	const category = Category.findByPk(id)
	if (!category) {
		throw new NotFoundError(`ID：为${id}的分类没找到`)
	}
	return category
}

/**
 *
 * @param req
 * @returns {{name, rank: (string|string|DocumentFragment|*)}}
 */

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{name, rank: (number|*)}}
 */
function filterBody(req) {
	return {
		name: req.body.name,
		rank: req.body.rank
	}
}

module.exports = router